properties([

   pipelineTriggers([
        cron('0 2 * * *')
    ]),

   buildDiscarder(
        logRotator(numToKeepStr: '100')
    ),

   parameters([
      [
         $class: 'ParameterSeparatorDefinition',
         name: 'DISTRIBUTE_HEADER',
         sectionHeader: '分发参数',
         separatorStyle: config.separatorStyle(),
         sectionHeaderStyle: config.sectionHeaderStyle()
      ],
      string(name: 'MAX_WORKES_PER_NODE', defaultValue: '500', description: '每次分发数量'),
      booleanParam(name: 'FORCE_REBUILD_LIBRARY', defaultValue: false, description: '强制重编译 Library ，master 编译清单时，worker dry-run 时执行重编译'),
      booleanParam(name: 'FORCE_REBUILD_ASSETBUNDLES', defaultValue: false, description: '强制重编译 AB 包，master 编译清单时执行'),

      [
         $class: 'ParameterSeparatorDefinition',
         name: 'IGNORE_HEADER',
         sectionHeader: 'Ignore 参数',
         separatorStyle: config.separatorStyle(),
         sectionHeaderStyle: config.sectionHeaderStyle()
      ],
      booleanParam(name: 'SKIP_PREPARE', defaultValue: false, description: '跳过准备阶段'),
      booleanParam(name: 'SKIP_BUILD_MANIFEST', defaultValue: false, description: '跳过编译清单阶段'),
      booleanParam(name: 'SKIP_DISTRIBUTE', defaultValue: false, description: '跳过分发任务阶段'),
      booleanParam(name: 'SKIP_BUILDGAME', defaultValue: false, description: '跳过编译游戏包阶段'),

      [
         $class: 'ParameterSeparatorDefinition',
         name: 'DEBUG_HEADER',
         sectionHeader: 'Debug 参数',
         separatorStyle: config.separatorStyle(),
         sectionHeaderStyle: config.sectionHeaderStyle()
      ],
      booleanParam(name: 'isdev', defaultValue: true, description: ''),
      booleanParam(name: 'isAutoconnectProfiler', defaultValue: true, description: '是否开启 profiler'),
      booleanParam(name: 'IS_DEBUG', defaultValue: true, description: '是否开启 debug'),
      booleanParam(name: 'isPoco', defaultValue: true, description: '是否接入 Poco'),
      booleanParam(name: 'isFlashFlower', defaultValue: true, description: '报错是否在游戏内显示'),
      booleanParam(name: 'isPreLoadAssets', defaultValue: true, description: '是否开启预加载'),
      booleanParam(name: 'uwa_enable', defaultValue: false, description: '开启UWA'),
      booleanParam(name: 'useLocalServer', defaultValue: false, description: '是否使用本地服务器列表'),
      booleanParam(name: 'selfSever', defaultValue: false, description: '是否插入自定义服务器'),
      string(name: 'serverName', defaultValue: 'JOY', description: ''),
      string(name: 'serverIp', defaultValue: '10.6.60.177', description: '版署 IP：154.8.222.226  外网展示:49.233.10.243  海外运营测试:129.211.97.178'),

      [
         $class: 'ParameterSeparatorDefinition',
         name: 'SDK_HEADER',
         sectionHeader: 'SDK 参数',
         separatorStyle: config.separatorStyle(),
         sectionHeaderStyle: config.sectionHeaderStyle()
      ],
      booleanParam(name: 'isBugly', defaultValue: true, description: '是否开启 bugly'),
      booleanParam(name: 'isSDKOPEN', defaultValue: false, description: '勾选开启SDK登录，不勾选直接使用账号登录'),
      booleanParam(name: 'isBuildAndroidProject', defaultValue: false, description: '勾选打安卓工程，不勾选打 APK'),

      [
         $class: 'ParameterSeparatorDefinition',
         name: 'Bundle_HEADER',
         sectionHeader: 'Bundle 编译参数',
         separatorStyle: config.separatorStyle(),
         sectionHeaderStyle: config.sectionHeaderStyle()
      ],
      booleanParam(name: 'assetbundle_mask', defaultValue: true, description: '是否加壳'),
      booleanParam(name: 'usebundleLoader', defaultValue: true, description: ''),
      booleanParam(name: 'containRootResFolder', defaultValue: false, description: ''),
      booleanParam(name: 'whetherToUpdateSVN', defaultValue: true, description: ''),
      booleanParam(name: 'skipBuildBundle', defaultValue: false, description: '是否跳过 Build AssetBundle'),
      booleanParam(name: 'rebuildAssetBundle', defaultValue: false, description: '是否 rebuildAssetBundle'),

      [
         $class: 'ParameterSeparatorDefinition',
         name: 'Package_HEADER',
         sectionHeader: 'Package 参数',
         separatorStyle: config.separatorStyle(),
         sectionHeaderStyle: config.sectionHeaderStyle()
      ],
      booleanParam(name: 'HotfixOpen', defaultValue: false, description: '是否开启热更'),
      booleanParam(name: 'AssetUseSubpackage', defaultValue: false, description: ''),
      choice(name: 'LuaEncrypt', choices: config.luaEncrypt(), description: 'None：不加密，Bytecode：字节码加密'),
      choice(name: 'AndroidBuildSystemSetting', choices: config.androidBuildSystemSetting(), description: ''),
      booleanParam(name: 'isObb', defaultValue: false, description: ''),
      string(name: 'meta_ClientChId', defaultValue: 'Build', description: '海外运营测试：Haiwai  海外CE测试：HWCE'),
      string(name: 'bundleversion', defaultValue: '0.0.1', description: '版本名'),
      string(name: 'bundlenumber', defaultValue: '1', description: '版本号，必须是增量正整数 如需增量热更必须+1'),
      string(name: 'HotfixChannel', defaultValue: 'and_local_test', description: ''),
      string(name: 'HotfixServerUrl', defaultValue: 'http://10.2.52.57:9001/hotfix/4,http://10.2.52.57:9001/hotfix/4', description: ''),
    ])
 ])

env.platform = "Android"
// deprecated
// env.assetbundle_mask = true
// env.rebuildAssetBundle = false

def projectName = 'Chijin'
// 对于 master 而言，mount 路径就是本地路径
def originProjectDir = config.mountProjectDir(projectName)
// 所有玩家都能读出来的路径，会写进 distribute.manifest 中
def sharedProjectDir = config.sharedProjectDir(projectName)

def masterNodeName = config.masterNodeName()

def workerJobName = 'distribute-android-assetbundle-worker'

def shouldRebuildLibrary()
{
   return config.shouldRebuild() || params.FORCE_REBUILD_LIBRARY
}

def rebuildLibraryArgvs()
{
   if(shouldRebuildLibrary())
      return " -rebuildlibrary "
   else
      return ""
}

def shouldRebuildAssetBundles()
{
   return config.shouldRebuild() || params.FORCE_REBUILD_ASSETBUNDLES
}

node("${masterNodeName}")
{
   stage("Prepare")
   {
      if(params.SKIP_PREPARE == false)
      {
         build job: config.upstreamJobName(), parameters: [
            booleanParam(name: "isdev", value: params.isdev),
            booleanParam(name: "isAutoconnectProfiler", value: params.isAutoconnectProfiler),
            booleanParam(name: "IS_DEBUG", value: params.IS_DEBUG),
            booleanParam(name: "isPoco", value: params.isPoco),
            booleanParam(name: "isFlashFlower", value: params.isFlashFlower),
            booleanParam(name: "isPreLoadAssets", value: params.isPreLoadAssets),
            booleanParam(name: "uwa_enable", value: params.uwa_enable),
            booleanParam(name: "useLocalServer", value: params.useLocalServer),
            booleanParam(name: "selfSever", value: params.selfSever),
            string(name: "serverName", value: params.serverName),
            string(name: "serverIp", value: params.serverIp),

            booleanParam(name: "isBugly", value: params.isBugly),
            booleanParam(name: "isSDKOPEN", value: params.isSDKOPEN),
            booleanParam(name: "isBuildAndroidProject", value: params.isBuildAndroidProject),

            booleanParam(name: "assetbundle_mask", value: params.assetbundle_mask),
            booleanParam(name: "usebundleLoader", value: params.usebundleLoader),
            booleanParam(name: "containRootResFolder", value: params.containRootResFolder),
            booleanParam(name: "whetherToUpdateSVN", value: params.whetherToUpdateSVN),
            booleanParam(name: "skipBuildBundle", value: params.skipBuildBundle),
            booleanParam(name: "rebuildAssetBundle", value: params.rebuildAssetBundle),

            booleanParam(name: "HotfixOpen", value: params.HotfixOpen),
            booleanParam(name: "AssetUseSubpackage", value: params.AssetUseSubpackage),
            string(name: "LuaEncrypt", value: params.LuaEncrypt),
            string(name: "AndroidBuildSystemSetting", value: params.AndroidBuildSystemSetting),
            booleanParam(name: "isObb", value: params.isObb),
            string(name: "meta_ClientChId", value: params.meta_ClientChId),
            string(name: "bundleversion", value: params.bundleversion),
            string(name: "bundlenumber", value: params.bundlenumber),
            string(name: "HotfixChannel", value: params.HotfixChannel),
            string(name: "HotfixServerUrl", value: params.HotfixServerUrl),

            string(name: "build_Name", value: "distribute${config.buildName()}"),
         ], quietPeriod: 0, wait: true, propagate: true


         // 创建Log目录
         def logDir = "${originProjectDir}/${config.distributeLogDir()}"
         sh "if [ ! -d ${logDir} ]; then ( mkdir -p ${logDir} ) fi"

         // 拷贝unity程序
         config.copyUnityDir("${masterNodeName}")

         // 开始前，删除所有可能因上次编译错误或者手动停止的lock
         utils.deleteAllLockFiles(projectName)

         // 准备工程，并在准备时，空跑一次
         utils.prepareProjectForAllNode(projectName, workerJobName, shouldRebuildLibrary(), params.assetbundle_mask)

         def svnProjectPath = config.mountProjectDir(projectName)
         utils.prepareSVNProject(svnProjectPath)
      }
   }

   stage('Build Manifest')
   {
      if(params.SKIP_BUILD_MANIFEST == false)
      {
         def logDir = "${originProjectDir}/${config.distributeLogDir()}"
         def logFilePath = "${logDir}/distribute${config.buildName()}.log"

         sh """
            ${config.localUnityPath(masterNodeName)} -quit -batchmode               \
            -projectPath ${originProjectDir}                                        \
            -target ${env.platform}                                                 \
            -graph Assets/AssetGraph.asset                                          \
            -executeMethod UnityEngine.AssetGraph.CUIUtility.BuildFromCommandline   \
            -logfile ${logFilePath}                                                 \
            -distributedMaster ${sharedProjectDir}                                  \
            -assetbundle_mask ${params.assetbundle_mask}                            \
            -rebuildBundle ${shouldRebuildAssetBundles()}                           \
            ${rebuildLibraryArgvs()}
         """
      }
   }

   stage('Distribute Tasks')
   {
      if(params.SKIP_DISTRIBUTE == false)
      {
         // 读清单文件，以获得要编译的ab包数量（即work数量）
         def mainfestFile = "${originProjectDir}/distribute.manifest"
         datas = readYaml (file: "${mainfestFile}")
         echo mainfestFile

         int paramsWorkesPerNode = params.MAX_WORKES_PER_NODE
         utils.distributeTask(projectName, workerJobName, datas.WorkCount, paramsWorkesPerNode, params.assetbundle_mask)

         utils.waitForAllTasksFinished(projectName)
      }
   }

   stage('Build Game')
   {
      if(params.SKIP_BUILDGAME == false)
      {
         // 拷贝打出来的 bundle 到 Game 目录
         config.copyBundlesToGameDir(projectName, masterNodeName, env.platform)

         // 编译 Game
         // build job: config.downstreamJobName(), parameters: [

         // ], quietPeriod: 0, wait: true, propagate: true
      }
   }
}
